package com.aizuda.service.interceptor;

import com.baomidou.kisso.SSOHelper;
import com.baomidou.kisso.annotation.LoginIgnore;
import com.baomidou.kisso.common.util.HttpUtil;
import com.baomidou.kisso.security.token.SSOToken;
import com.baomidou.kisso.web.interceptor.SSOSpringInterceptor;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;

import java.lang.reflect.Method;

/**
 * @author hjw
 * @description
 * @date 2025年06月25日 16:26
 */
public class MySSOSpringInterceptor extends SSOSpringInterceptor {
    private static final Logger log = LoggerFactory.getLogger(MySSOSpringInterceptor.class);


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod handlerMethod) {
            Method method = handlerMethod.getMethod();
            LoginIgnore loginIgnore = (LoginIgnore) method.getAnnotation(LoginIgnore.class);
            if (null != loginIgnore) {
                return true;
            }

            SSOToken ssoToken = SSOHelper.getSSOToken(request);
            if (ssoToken == null) {
                if (HttpUtil.isAjax(request)) {
                    this.getHandlerInterceptor().preTokenIsNullAjax(request, response);
                    return false;
                }

                if (this.getHandlerInterceptor().preTokenIsNull(request, response)) {
                    log.debug("logout. request url:" + request.getRequestURL());
                    SSOHelper.clearRedirectLogin(request, response);
                }
                log.info("logout. request url:" + request.getRequestURL());
                return false;
            }

            request.setAttribute("kissoTokenAttr", ssoToken);
        }

        return true;
    }
}
